package com.zhiyun.yycall.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

import com.everysoft.autoanswer.AutoAnswerIntentService;
import com.zhiyun.yycall.YYCallController;

public class CallInReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

		String phone = intent
				.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
		if (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) {

			// 在回拨的网络请求发出去之后，回拨还没接通之前，有其它正常的电话过来，则取消掉本次回拨
			YYCallController controller = YYCallController
					.getLateastController();
			if (controller == null) {
				return;
			}

			if (!controller.canAutoAnswer(phone)) {
				controller.stopCallback();
				return;
			}

			controller.stopPollCallingStatus();
			controller.sendMsg(String.format("云之呼已接通%s...\n即将进入接听界面",
					controller.getTargetNo()));

			// 开始自动接听流程
			startAutoAnswerService(controller, context);

		}

	}

	private void startAutoAnswerService(YYCallController controller,
			Context context) {
		// 自动接通回拨进来的号码...
		try {
			Intent autoAnswerintent = new Intent(context,
					AutoAnswerIntentService.class);
			autoAnswerintent.putExtra("controllerId",
					controller.getControllerId());
			context.startService(autoAnswerintent);
		} catch (Exception e) {
			controller.stopCallback();

		}

	}

}
